package com.edu.hre.struts.action.survey;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreSurveyEmpAnswer;
import com.edu.hre.db.pojo.HreSurveyQuestion;
import com.edu.hre.db.pojo.HreSurveyQuestionAnswer;
import com.edu.hre.db.pojo.HreSurveyTopic;
import com.edu.hre.db.pojo.HreSubunit;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.pojo.HreUserRoleScreen;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.survey.SurveyManagementListForm;
import com.edu.hre.struts.form.survey.SurveyTakeListForm;
import com.edu.hre.struts.form.survey.SurveyTakeUpdateForm;

public class SurveyTakeUpdateAction extends DispatchAction {
	
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		HreUserRoleScreen userRoleScreen = (HreUserRoleScreen) request.getSession().getAttribute(RequestUtils.Attribute.HreUserRoleScreen);
		HreUser user = (HreUser) request.getSession().getAttribute(RequestUtils.Attribute.USER_INFO);
		SurveyTakeUpdateForm beanForm = (SurveyTakeUpdateForm) form;
		int id = Integer.parseInt(request.getParameter("id"));
		HreSurveyTopic topic = baseService.getPojo(id, HreSurveyTopic.class);
		if(request.getParameter("btnAdd") == null){ 
			String html = "";
			if(topic.getSubunitId() != 1) {// 1 == rootId
				HreEmployee employee = baseService.getFirstPojo("empNumber", Compare.EQUAL, user.getEmpNumber(), null, null, 0, HreEmployee.class);
				if(employee != null && employee.getWorkStation() != null && employee.getWorkStation() >= 0){
					List<Integer> listIdSubunit = new ArrayList<Integer>();
					HreSubunit subunit = baseService.getPojo(employee.getWorkStation(), HreSubunit.class);
					SurveyTakeListAction.getListParentsSubunit(subunit, listIdSubunit);
					if(!listIdSubunit.contains(topic.getSubunitId())){
						html = "You don't have permission to take this survey!";
						response.getWriter().write(html);
						return null;
					}
				}
				else {
					html = "You don't have permission to take this survey!";
					response.getWriter().write(html);
					return null;
				}
			}
			if(topic.getStartDate().compareTo(new Date()) > 0 || topic.getEndDate().compareTo(new Date()) < 0){
				html = "Invalid time to take this survey!";
				response.getWriter().write(html);
				return null;
			}
			HreSurveyEmpAnswer empAns = baseService.getFirstPojoAnd(
					new String[]{"userId", "topicId"}, 
					new int[]{Compare.EQUAL, Compare.EQUAL}, 
					new Object[]{user.getId(), topic.getId()}, HreSurveyEmpAnswer.class);
			if(empAns != null){
				html = "You have already taken this survey!";
				response.getWriter().write(html);
				return null;
			}
			
			html += "<center><h2>Topic: " + topic.getName() + "</h2></center><br/>\n";
			
			List<HreSurveyQuestion> listQuestion = baseService.getPojos("topicId", Compare.EQUAL, topic.getId(), new String[]{"rank"}, new Boolean[]{false}, 0, 0, HreSurveyQuestion.class);
			for(int i = 0; listQuestion != null && i < listQuestion.size(); i ++){
				html += "<div class='question'><br/><hr/>";
				HreSurveyQuestion question = listQuestion.get(i);
				html += "<center><h3>Question " + (i + 1) + "</h3></center>";
				html += "<h4>" + question.getText() + "</h4>";
				List<HreSurveyQuestionAnswer> listAnswer = baseService.getPojos("questionId", Compare.EQUAL, question.getId(), new String[]{"label"}, new Boolean[]{false}, 0, 0, HreSurveyQuestionAnswer.class);
				for(int k = 0; listAnswer != null && k < listAnswer.size(); k ++){
					HreSurveyQuestionAnswer answer = listAnswer.get(k);
					if(question.getType() == 1){ // multi choice
						String nameCheckbox = "checkbox_" + question.getId() + "_" + answer.getId();
						html += "<input type='checkbox' name='" + nameCheckbox + "'>" + answer.getText() + "</input>";
					} else {
						String nameRadio = "radio_" + question.getId();
						if(listAnswer.size() > 1){
							html += "<input type='radio' value='" + answer.getId() + "' name='" + nameRadio + "'>" + answer.getText() + "</input>";
						} else {
							html += "<input checked type='radio' value='" + answer.getId() + "' name='" + nameRadio + "'>" + answer.getText() + "</input>";
						}
					}
					if(answer.getType() == 2){ // free text
						String nameTextbox = "text_" + question.getId() + "_" + answer.getId();
						html += "<br/><a style='padding-left:20px;'><a>" +
								"<textarea type='text' name='" + nameTextbox 
								+ "' style='width:655px;height:40px;'></textarea><br/>";
					} else {
						html += "<br/>";
					}
				}
				html += "</div>";
			}
			html = html.replace("'", "\"");
			beanForm.setId(id);
			beanForm.setHtml(html);
			return mapping.findForward("surveyTakeUpdate");
		} else {
			System.out.println("Adding: " + request.getParameter("btnAdd"));
			List<HreSurveyQuestion> listQuestion = baseService.getPojos("topicId", Compare.EQUAL, topic.getId(), new String[]{"rank"}, new Boolean[]{false}, 0, 0, HreSurveyQuestion.class);
			for(int i = 0; listQuestion != null && i < listQuestion.size(); i ++){
				HreSurveyQuestion question = listQuestion.get(i);
				List<HreSurveyQuestionAnswer> listAnswer = baseService.getPojos("questionId", Compare.EQUAL, question.getId(), new String[]{"label"}, new Boolean[]{false}, 0, 0, HreSurveyQuestionAnswer.class);
				for(int k = 0; listAnswer != null && k < listAnswer.size(); k ++){
					HreSurveyQuestionAnswer answer = listAnswer.get(k);
					String nameTextbox = "text_" + question.getId() + "_" + answer.getId();
					if(question.getType() == 1){  // multi choice
						String nameCheckbox = "checkbox_" + question.getId() + "_" + answer.getId();
						if("on".equalsIgnoreCase(request.getParameter(nameCheckbox))){
							HreSurveyEmpAnswer empAnswer = new HreSurveyEmpAnswer(answer.getType(), answer.getId(), null, user.getId(), topic.getId());
							if(answer.getType() == 2 && StringUtils.isNotBlank(request.getParameter(nameTextbox))){ // free text
								empAnswer.setFreetext(request.getParameter(nameTextbox));
							}
							baseService.save(empAnswer);
						}
					} else {
						String nameRadio = "radio_" + question.getId();
						if(String.valueOf(answer.getId()).equalsIgnoreCase(request.getParameter(nameRadio))){
							HreSurveyEmpAnswer empAnswer = new HreSurveyEmpAnswer(answer.getType(), answer.getId(), null, user.getId(), topic.getId());
							if(answer.getType() == 2 && StringUtils.isNotBlank(request.getParameter(nameTextbox))){ // free text
								empAnswer.setFreetext(request.getParameter(nameTextbox));
							}
							baseService.save(empAnswer);
							break;
						}
					} 
				}
			}
			return new ActionForward("surveyTakeList.do", true);
		} 
	}
}
